#include <QString>
#include <QDebug>

#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

#include "databasemanager.h"
#include "interface/mensagem.h"

DataBaseManager *DataBaseManager::getInstance() {
    static DataBaseManager *instance=NULL;
    if (!instance) instance = new DataBaseManager();

    return instance;
}

DataBaseManager::DataBaseManager() {
  db = QSqlDatabase::addDatabase("QSQLITE");

  if (!setDB("tsunami.db3")) {
      Mensagem::erro("Erro", "Erro ao abrir banco de dados!");
  }
}

void DataBaseManager::close() {
  if (db.isOpen())
    db.close();
}

bool DataBaseManager::setDB(const char *name) {
  if (db.isOpen())
    db.close();

  db.setDatabaseName(name);

  return db.open();
}


void DataBaseManager::exec(QString query) {
    QSqlQuery qSqlQuery;

    qSqlQuery.prepare(query);
    if (!qSqlQuery.exec())
        qDebug() << "Erro ao execultar: " << query << " " << qSqlQuery.lastError().text();
}


void DataBaseManager::openTransaction() {
    this->exec("BEGIN TRANSACTION");
}

void DataBaseManager::endTransaction() {
    this->exec("END TRANSACTION");
}
